package people.paper.tv;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;

import com.skyworth.util.imageloader.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import people.paper.tv.utils.monitor.Monitor;

public class BaseApplication extends Application {
    private static final Handler uiHandler = new Handler(Looper.getMainLooper());

    public static final void runOnUiThread(Runnable runnable) {
        if (Looper.getMainLooper() == Looper.myLooper())
            runnable.run();
        else
            uiHandler.post(runnable);
        //xxx
    }

    private static Context context;

    public static final Context getContext() {
        return context;
    }

    public static final boolean isNetConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable() && info.isConnected())
            return true;
        else
            return false;
    }


    public static int getVersionCode() {
        PackageManager mPackageManager = context.getPackageManager();
        try {
            return mPackageManager.getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            return -1;
        }
    }

    public static String getVersionName() {
        PackageManager mPackageManager = context.getPackageManager();
        try {
            return mPackageManager.getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            return "bad version name";
        }
    }

    public static void killSelf() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        Monitor.start(context, "target1");
        initUmeng();
        ImageLoader.getLoader().init(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                e.printStackTrace();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
    }

    private void initUmeng() {
        UMConfigure.init(this, BuildConfig.UMENG_APPKEY, BuildConfig.UMENG_CHANNEL, UMConfigure.DEVICE_TYPE_BOX, null);
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        UMConfigure.setEncryptEnabled(!BuildConfig.DEBUG);
        MobclickAgent.openActivityDurationTrack(false);
    }
}
